<?php
$cc_type = 'msw';
foreach ($data as $data_k => $data_v) {
  $pass = 1;
  $update = 0;
  $node = NULL;
  $fe = array();
  $cc = NULL;
  $ccnode = NULL;
  $cctax = NULL;

  $rowcount = $context['results']['row'];
  _flog($log_file, "-- row $rowcount --");

  _flog($log_file, '-- prepare a new record --');
  $check_suffix = array('_zh', '_gb', '_01', '_02', '_03', '_04', '_05');
  $fec = array();
  $images = array();
  $fmatch = array_flip($match);

  if (!empty($existing_nid)) {
    _flog($log_file, "-- Load existing $existing_nid --");
    $update = 1;
    $ccnode = node_load($existing_nid);
  }
  /*$existing_nid = $data[$data_k][$fmatch['nid']];
  if (!empty($existing_nid)) {
    _flog($log_file, "-- Load existing $existing_nid --");
    $update = 1;
    $cc = node_load($existing_nid);
  }*/
  if (empty($ccnode)) {
    $ccnode = new stdClass();
    $ccnode->type='msw';
  }

  foreach ($data_v as $rowk => $rowv) {

    $fn = $match[$rowk];
    $is_msw_tax = 0;
    if (substr($fn, 0, 4) == 'tax_') {
        $is_msw_tax = 1;
        $fn = substr($fn, 4, strlen($fn));
        $cc = $cctax;
    }
    else {
      $cc = $ccnode;
    }

    $lang = 'und';

    $suffix = substr($fn, -3);
    $delta = 0;
    if (in_array($suffix, $check_suffix)) {
      $fn = substr($fn, 0, -3);
      if ($suffix == '_gb') {
        $lang = 'zh-hans';
      }
      if ($suffix == '_zh') {
        $lang = 'zh-hant';
      }
      if ($suffix == '_01') {
        $delta = 1;
      }
      if ($suffix == '_02') {
        $delta = 2;
      }
      if ($suffix == '_03') {
        $delta = 3;
      }
      if ($suffix == '_04') {
        $delta = 4;
      }
      if ($suffix == '_05') {
        $delta = 5;
      }
      $suffix = substr($fn, -3);
      if (in_array($suffix, $check_suffix)) {
        $fn = substr($fn, 0, -3);
        if ($suffix == '_gb') {
          $lang = 'zh-hans';
        }
        if ($suffix == '_zh') {
          $lang = 'zh-hant';
        }
      }
    }
    $info = field_info_field($fn);
    if (!empty($info['translatable']) && $lang == 'und') {
      $lang = 'und';
    }
    if (!empty($info)) {
      $type = $info['type'];
      $cols = count($info['columns']);
      $fieldname = $info['field_name'];
      $instance = field_info_instance('node', $info['field_name'], $cc_type);
      /*if (empty($instance)) {
        $instance = field_info_instance('field_collection_item', $info['field_name'], 'field_slideshow');
        $fec['field_slideshow'][] = $fieldname;
      }*/
      $label = $instance['label'];
      switch ($type) {
      case "list_boolean":
        if ($rowv == '') {
          $cc->{$fieldname}[$lang][0]['value'] = '';
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          $ori_val = $rowv;
          if (!$rowv) {
            _flog($log_file, "-- invalid $label - $rowv--");
          }
          else {
            $oldval = '';
            if (!empty($cc->{$fieldname}[$lang][0]['value'])) {
              $oldval = $cc->{$fieldname}[$lang][0]['value'];
            }
            if ($update) {
              _flog($log_file, "-- modify $label - $oldval - $ori_val --");
            }
            else {
              _flog($log_file, "-- add $label - $ori_val --");
            }
            $cc->{$fieldname}[$lang][0]['value'] = 1;
          }
        }
        break;
            /*case "number_integer":
            case "number_float":
                if ($rowv == '-') {
                    $cc->{$fieldname}[$lang][0]['value'] = '';
                    _flog($log_file, "-- remove $label --");
                }
                elseif (empty($rowv)) {
                    _flog($log_file, "-- skip $label --");
                }
                else {
                    $ori_val = $rowv;
                    if (!$rowv) {
                        _flog($log_file, "-- invalid $label - $rowv--");
                    }
                    else {
                        $oldval = '';
                        if (!empty($cc->{$fieldname}[$lang][0]['value'])) {
                            $oldval = $cc->{$fieldname}[$lang][0]['value'];
                        }
                        if ($update) {
                            _flog($log_file, "-- modify $label - $oldval - $ori_val --");
                        }
                        else {
                            _flog($log_file, "-- add $label - $ori_val --");
                        }
                        $cc->{$fieldname}[$lang][0]['value'] = $ori_val;
                    }
                }
            break;*/
      case "commerce_price":
        if ($rowv == '') {
          $cc->{$fieldname}[$lang] = array();
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          $ori_val = $rowv;
          if (!$rowv) {
            _flog($log_file, "-- invalid $label - $rowv--");
          }
          else {
            $oldval = '';
            if (!empty($cc->{$fieldname}[$lang][0]['amount'])) {
              $oldval = $cc->{$fieldname}[$lang][0]['amount'];
            }
            if ($update) {
              _flog($log_file, "-- modify $label - $oldval - $ori_val --");
            }
            else {
              _flog($log_file, "-- add $label - $ori_val --");
            }
            $cc->{$fieldname}[$lang][0]['amount'] = (float)str_replace(array('-',','),'',$ori_val);
            $cc->{$fieldname}[$lang][0]['currency_code'] = 'HKD';
          }
        }
        break;
      case "entityreference":
        if ($rowv == '') {
          $cc->{$fieldname}[$lang][0]['target_id'] = '';
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          $ori_val = $rowv;
          if (!is_numeric($rowv)) {
            _flog($log_file, "-- invalid $label - $rowv--");
          }
          else {
            $oldval = '';
            if (!empty($cc->{$fieldname}[$lang][0]['target_id'])) {
              $oldval = $cc->{$fieldname}[$lang][0]['target_id'];
            }
            if ($update) {
              _flog($log_file, "-- modify $label - $oldval - $ori_val --");
            }
            else {
              _flog($log_file, "-- add $label - $ori_val --");
            }
            $cc->{$fieldname}[$lang][0]['target_id'] = $ori_val;
          }
        }
        break;
      case "taxonomy_term_reference":
        $vob = @$info['settings']['allowed_values'][0]['vocabulary'];
        $vob = taxonomy_vocabulary_machine_name_load($vob);
        $vid = $vob->vid;
        $tax = current(taxonomy_get_term_by_name($rowv, $vob->machine_name));
        if (empty($tax)) {
            tax = new stdClass();
            $tax->vid = $vid;
            $tax->name = $rowv;
            taxonomy_term_save($tax);
        }
        $cc->{$fieldname}[$lang][0]['tid'] = $tax->tid;
        break;
      case "list_text":
        if ($rowv == '') {
          $cc->{$fieldname}[$lang][0]['value'] = '';
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          $ori_val = $rowv;
          jessica_ipt_list2val($fieldname, $rowv);
          if (!$rowv) {
            _flog($log_file, "-- invalid $label - $rowv--");
          }
          else {
            $oldval = '';
            if (!empty($cc->{$fieldname}[$lang][0]['value'])) {
              $oldval = $cc->{$fieldname}[$lang][0]['value'];
              jessica_ipt_list2val($fieldname, $oldval);
            }
            if ($update) {
              _flog($log_file, "-- modify $label - $oldval - $ori_val --");
            }
            else {
              _flog($log_file, "-- add $label - $ori_val --");
            }
            $cc->{$fieldname}[$lang][0]['value'] = $ori_val;
          }
        }
        break;
      case "number_integer":
      case "number_float":
        if ($rowv == '') {
          $cc->{$fieldname}[$lang] = array();
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          if ($rowv == '') {
            $rowv = '';
          }
          $oldval = '';
          if (!empty($cc->{$fieldname}[$lang][0]['value'])) {
            $oldval = $cc->{$fieldname}[$lang][0]['value'];
          }
          if (!is_numeric($rowv)) {
            _flog($log_file, "-- invalid format  $label  - $rowv --");
            continue;
          }
          if ($update) {
            _flog($log_file, "-- modify $label - $oldval - $rowv --");
          }
          else {
            _flog($log_file, "-- add $label - $rowv --");
          }
          $cc->{$fieldname}[$lang][0]['value'] = $rowv;
        }
        break;
      case "link_field":
        if ($rowv == '') {
          $cc->{$fieldname}[$lang] = array();
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          if ($rowv == '') {
            $rowv = '';
          }
          $oldval = '';
          $link_arr = explode('|', $rowv);
          $title = $link_arr[0];
          $url = $link_arr[1];
          if (!empty($cc->{$fieldname}[$lang][0][$attr])) {
            $oldval = $cc->{$fieldname}[$lang][0][$attr];
          }
          if ($update) {
            _flog($log_file, "-- modify $label - $oldval - $rowv --");
          }
          else {
            _flog($log_file, "-- add $label - $rowv --");
          }
          $cc->{$fieldname}[$lang][0]['title'] = $title;
          $cc->{$fieldname}[$lang][0]['url'] = $url;
        }
        break;
      case "text":
      case "text_with_summary":
      case "text_long":
        if ($rowv == '') {
          $cc->{$fieldname}[$lang][$delta] = array();
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          if ($rowv == '') {
            $rowv = '';
          }
          $oldval = '';
          if (!empty($cc->{$fieldname}[$lang][$delta]['value'])) {
            $oldval = $cc->{$fieldname}[$lang][$delta]['value'];
          }
          if ($update) {
            _flog($log_file, "-- modify $label - $oldval - $rowv --");
          }
          else {
            _flog($log_file, "-- add $label - $rowv --");
          }
          $cc->{$fieldname}[$lang][$delta]['value'] = $rowv;
        }
        break;
      case "image":
        $cc->{$fieldname}[$lang][$delta] = array();
        if ($rowv == '') {
          $cc->{$fieldname}[$lang][$delta] = array();
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          if ($rowv == '') {
            $rowv = '';
          }
          $oldval = '';
          if (!empty($cc->{$fieldname}[$lang][$delta]['fid'])) {
            $oldval = $cc->{$fieldname}[$lang][$delta]['fid'];
          }
          if ($update) {
            _flog($log_file, "-- modify $label - $oldval - $rowv --");
          }
          else {
            _flog($log_file, "-- add $label - $rowv --");
          }
          $images[$fieldname][$lang][$delta] = $rowv;
        }
        break;
      case "datetime":
        $rowv = (int)$rowv;
        $rowv = strtotime($rowv);
        $rowv = format_date($rowv, 'custom', 'Y-m-d H:i:s');
        if ($rowv == '') {
          $cc->{$fieldname}[$lang] = array();
          _flog($log_file, "-- remove $label --");
        }
        elseif (empty($rowv)) {
          _flog($log_file, "-- skip $label --");
        }
        else {
          $oldval = '';
          if (!empty($cc->{$fieldname}[$lang][0]['value'])) {
            $oldval = $cc->{$fieldname}[$lang][0]['value'];
          }
          if ($update) {
            _flog($log_file, "-- modify $label - $oldval - $rowv --");
          }
          else {
            _flog($log_file, "-- add $label - $rowv --");
          }
          $cc->{$fieldname}[$lang][0]['value'] = $rowv;
        }
        break;
      }
    }
    else {
      switch ($fn) {
      case "title":
        if (!empty($rowv)) {
          $cc->title = $rowv;
        }
        break;
      case "status":
        if (!empty($rowv)) {
          $cc->status = 1;
        }
        else {
          $cc->status = 0;
        }
        break;
      case "ring_size_mode":
        if (empty($rowv)) {
          continue;
        }
        $temp = jessica_ipt_set_attributes($rowv, 1);
        $temp = $temp[LANGUAGE_NONE][0]['set_details']['field_ring_size'];
        _flog($log_file, "-- add / modify - ring size mode 1 - $rowv --");
        $cc->field_settings[LANGUAGE_NONE][0]['set_id'] = 'ring_setting';
        $cc->field_settings[LANGUAGE_NONE][0]['set_details']['field_ring_size'] = $temp;
        break;
      case "ring_size_mode2":
        if (empty($rowv)) {
          continue;
        }
        $temp = jessica_ipt_set_attributes($rowv, 2);
        $temp = $temp[LANGUAGE_NONE][0]['set_details']['field_ring_size_2'];
        _flog($log_file, "-- add / modify - ring size mode 2 - $rowv --");
        $cc->field_settings[LANGUAGE_NONE][0]['set_details']['field_ring_size_2'] = $temp;
        break;
      case "default":
        _flog($log_file, "-- $fn not found --");
        break;
      }
    }
    if ($is_msw_tax) {
        $cctax = $cc;
    }
    else {
        $ccnode = $cc;
    }
  }

  $status = $pass ? "success" : "failed";
  if ($pass) {
    if ($mode == 'test') {
      foreach ($images as $image_field => $lang_obj) {
        foreach ($lang_obj as $lang_k => $img_obj) {
          foreach ($img_obj as $imig_k => $img_v) {
            $img_v = str_replace('.jpg.jpg', '.jpg', $img_v);
            $img_v = str_replace(' .jpg', '.jpg', $img_v);
            $img_v = str_replace(' .png', '.png', $img_v);
            $img_v = str_replace('.png.png', '.png', $img_v);
            if (!empty($img_v)) {
              $file->uri = 'private://import/' . $img_v;
              if (!file_exists($file->uri)) {
                _flog($log_file, "file not exists : $img_v");
                continue;
              }
              $file = new stdClass();
              $file->filemime = file_get_mimetype($file->uri);
              $file->status = FILE_STATUS_PERMANENT;
              $ccnode->{$image_field}[$lang_k][$img_k] = (array)$file;
            }
          }
        }
      }
      $fe = array();
      foreach ($fec as $fe_name => $fefns) {
        $fefns = array_unique($fefns);
        foreach ($fefns as $fefn) {
          $fec_arr = $cc->{$fefn};
          unset($cc->{$fefn});
          if (!empty($fec_arr)) {
            foreach ($fec_arr as $fec_lang => $fec_obj) {
              if ($fec_lang == 'und') {
                $fec_lang = 'und';
              }
              foreach ($fec_obj as $fec_obj_k => $fec_obj_v) {
                $fetemp = NULL;
                if (empty($fe[$fe_name][$fec_lang][$fec_obj_k])) {
                  if ($update && !empty($cc->{$fe_name}[$fec_lang][$fec_obj_k]['value'])) {
                    //$fe[$fe_name][$fec_lang][$fec_obj_k] = field_collection_item_load($cc->{$fe_name}[$fec_lang][0]['value']);
                    $fetemp = field_collection_item_load($cc->{$fe_name}[$fec_lang][$fec_obj_k]['value']);
                  }
                  else {
                    //$fe[$fe_name][$fec_lang][$fec_obj_k] = entity_create('field_collection_item', array('field_name' => $fe_name));
                    $fetemp = entity_create('field_collection_item', array('field_name' => $fe_name));
                  }
                  $fe[$fe_name][$fec_lang][$fec_obj_k] = clone $fetemp;
                }
                $fe[$fe_name][$fec_lang][$fec_obj_k]->{$fefn}['und'][0] = $fec_obj[$fec_obj_k];

                //$fe[$fe_name][$fec_lang][$fec_obj_k]->{$fefn}['und'][0] = $fec_obj[$fec_obj_k];
              }
            }
          }
        }
      }
      foreach ($fe[$fe_name] as $fev_lang => $fev) {
        foreach ($fev as $fevv) {
          if (empty($fevv->item_id)) {
            $fevv->is_new = TRUE;
            $fevv->setHostEntity('node', $cc, $fev_lang);
          }
          $fevv->save(true);
        }
      }
      dsm($cc);
      dsm($fe);
    }
    if ($mode == 'import') {
      foreach ($images as $image_field => $image_v) {
        foreach ($image_v as $lang_k => $img_obj) {
          foreach ($img_obj as $img_k => $img_v) {
            $img_v = str_replace('.jpg.jpg', '.jpg', $img_v);
            $img_v = str_replace(' .jpg', '.jpg', $img_v);
            $img_v = str_replace(' .png', '.png', $img_v);
            $img_v = str_replace('.png.png', '.png', $img_v);
            $img_v = trim($img_v);
            if (!empty($img_v)) {
              $file = new stdClass();
              $file->uri = 'private://import/' . $img_v;
              if (!file_exists($file->uri)) {
                _flog($log_file, "file not exists : $img_v");
                continue;
              }
              $file->filemime = file_get_mimetype($file->uri);
              $file->status = FILE_STATUS_PERMANENT;
              $file = file_copy($file, 'public://', FILE_EXISTS_REPLACE);
              file_usage_add($file, 'jessica_ipt', 'csv', 1);
              $ccnode->{$image_field}[$lang_k][$img_k] = (array)$file;
            }
          }
        }
      }

      $cc->type = $cc_type;

      $fe = array();
      foreach ($fec as $fe_name => $fefns) {
        $fefns = array_unique($fefns);
        foreach ($fefns as $fefn) {
          $fec_arr = $cc->{$fefn};
          unset($cc->{$fefn});
          if (!empty($fec_arr)) {
            foreach ($fec_arr as $fec_lang => $fec_obj) {
              if ($fec_lang == 'und') {
                $fec_lang = 'und';
              }
              $fec_obj = array_filter($fec_obj);
              foreach ($fec_obj as $fec_obj_k => $fec_obj_v) {
                $fetemp = NULL;
                if (empty($fe[$fe_name][$fec_lang][$fec_obj_k])) {
                  if ($update && !empty($cc->{$fe_name}[$fec_lang][$fec_obj_k]['value'])) {
                    //$fe[$fe_name][$fec_lang][$fec_obj_k] = field_collection_item_load($cc->{$fe_name}[$fec_lang][0]['value']);
                    $fetemp = field_collection_item_load($cc->{$fe_name}[$fec_lang][$fec_obj_k]['value']);
                  }
                  else {
                    //$fe[$fe_name][$fec_lang][$fec_obj_k] = entity_create('field_collection_item', array('field_name' => $fe_name));
                    $fetemp = entity_create('field_collection_item', array('field_name' => $fe_name));
                  }
                  $fe[$fe_name][$fec_lang][$fec_obj_k] = clone $fetemp;
                }
                $fe[$fe_name][$fec_lang][$fec_obj_k]->{$fefn}['und'][0] = $fec_obj[$fec_obj_k];

                //$fe[$fe_name][$fec_lang][$fec_obj_k]->{$fefn}['und'][0] = $fec_obj[$fec_obj_k];
              }
            }
          }
        }
      }
      foreach ($fe[$fe_name] as $fev_lang => $fev) {
        foreach ($fev as $fevv) {
          if (empty($fevv->item_id)) {
            $fevv->is_new = TRUE;
            $fevv->setHostEntity('node', $cc, $fev_lang);
          }
          $fevv->save(true);
        }
      }
    if (!empty($cctax)) {
        $cctax->name = @$cctax->name_field[LANGUAGE_NONE][0]['value'];
        taxonomy_term_save($cctax);
    }
    if (!empty($cctax->tid)) {
      $ccnode->field_profile[LANGUAGE_NONE][0]['tid'] = $cctax->tid;
    }
$ccnode->uid = 1;
    node_save($ccnode);

    }
    $context['results']['success']++;
  }
  else {
    $context['results']['failed']++;
  }
  _flog($log_file, "-- row $rowcount $status --");
  $context['results']['row']++;
}


